package com.lhx.wechat.servlet;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.lhx.wechat.entity.message.Article;
import com.lhx.wechat.entity.message.NewsMessage;
import com.lhx.wechat.utils.IWechatCall;
import com.lhx.wechat.utils.WechatMessageUtil;

/**
 *  消息返回
 */
public class LhxWechatCall extends IWechatCall {
	
	private LhxWechatCall(){
	}
	
	private static LhxWechatCall instance = new LhxWechatCall();
	
	public static LhxWechatCall getInstance(){
		return instance;
	}
	
    @Override
    public String callFunction(Map<String, String> requestMap) {

        String msgType = requestMap.get("MsgType");
        // 发送方帐号（open_id）
        String fromUserName = requestMap.get("FromUserName");
        // 公众帐号
        String toUserName = requestMap.get("ToUserName");
        // 消息内容
        String content = requestMap.get("Content");

        //文本内容
        if (msgType.equals(WechatMessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
            return super.buildAutoResponse(fromUserName, toUserName, content);
        }

        // 事件推送
        if (msgType.equals(WechatMessageUtil.REQ_MESSAGE_TYPE_EVENT)) {

            String eventType = requestMap.get("Event");
            // 订阅
            if (eventType.equals(WechatMessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                List<Article> articleList = new ArrayList<>();
                Article article = new Article();
                article.setTitle("亲，感谢您关注本微信号。");
                article.setDescription("欢迎您关注本微信号，本微信号为个人测试所用，暂不推送其他相关信息，如期间收到任何消息，造成的损失，本人概不负责。再次感谢您的关注，谢谢。");
                article.setPicUrl("http://img.longhongxing.com/public/1.jpg");
                article.setUrl("http://www.longhongxing.com");
                articleList.add(article);

                NewsMessage newsMessage = super.newNewsMsg(fromUserName, toUserName, articleList);

                return WechatMessageUtil.newsMessageToXml(newsMessage);
            }

            //自定义菜单点击事件
            if (eventType.equals(WechatMessageUtil.EVENT_TYPE_CLICK)) {
                // 事件KEY值，与创建自定义菜单时指定的KEY值对应
                String eventKey = requestMap.get("EventKey");
                if (eventKey.equals("online-service")) { //在线客服
                    return super.buildOnlineService(fromUserName, toUserName);
                }

            }
        }

        return null;
    }
}
